<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-form-item label="排班日期">
              <el-date-picker v-model="searchForm.scheduleDate" type="date" placeholder="选择排班日期"
                value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <el-form-item label="结束日期">
              <el-date-picker v-model="searchForm.endDate" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <el-form-item label="班次">
              <el-select v-model="searchForm.shiftId" placeholder="请选择班次" clearable style="width: 100%">
                <el-option v-for="item in classOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <el-form-item label="值班人员">
              <el-select v-model="searchForm.userId" placeholder="请选择值班人员" clearable style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <el-form-item label="周期类型">
              <el-select v-model="searchForm.cycleType" placeholder="请选择周期类型" clearable style="width: 100%">
                <el-option v-for="item in cycleTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div class="form-actions">
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon class="el-icon--left">
                  <Search />
                </el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch">
                <el-icon class="el-icon--left">
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card mt-2">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon class="el-icon--left">
            <Plus />
          </el-icon>
          新增排班
        </el-button>
        <el-button type="success" @click="handleSubstitute">
          <el-icon class="el-icon--left">
            <User />
          </el-icon>
          申请顶班
        </el-button>
        <el-button type="warning" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon class="el-icon--left">
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      </div>
      <el-table :data="tableData" v-loading="loading" border style="width: 100%"
        @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="id" label="ID" align="center" width="80" />

        <el-table-column prop="scheduleDate" label="排班日期" align="center">
          <template #default="{ row }">
            <span>{{ row.scheduleDate }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="endDate" label="结束日期" align="center">
          <template #default="{ row }">
            <span>{{ row.endDate }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="userId" label="值班人员" align="center">
          <template #default="{ row }">
            <span>{{ getName(userOptions, row.userId, 'id', 'name') }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="cycleType" label="周期类型" align="center">
          <template #default="{ row }">
            <el-tag :type="getCycleTypeTag(row.cycleType)">
              {{ getCycleTypeText(row.cycleType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="cycleValue" label="周期值" align="center">
          <template #default="{ row }">
            <span>{{ row.cycleValue }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button v-if="row.status === 1" type="success" link size="small" @click="handleApprove(row)">
              审核通过
            </el-button>
            <el-button v-if="row.status === 1" type="danger" link size="small" @click="handleReject(row)">
              审核驳回
            </el-button>
            <el-button v-if="row.status === 2" type="info" link size="small" @click="handleComplete(row)">
              标记完成
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="tableData.length > 0">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="排班详情" width="800px" :before-close="handleCloseViewDialog">
      <div v-if="currentDetail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="排班ID">{{ currentDetail.id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="排班日期">{{ currentDetail.scheduleDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ currentDetail.endDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="班次">{{ getClassName(currentDetail.shiftId) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="值班人员">{{ getUserName(currentDetail.userId) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="周期类型">{{ getCycleTypeText(currentDetail.cycleType) || '-'
          }}</el-descriptions-item>
          <el-descriptions-item label="周期值">{{ currentDetail.cycleValue || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentDetail.status)" size="small">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createTime) || '-'
          }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.updateTime) || '-'
          }}</el-descriptions-item>
        </el-descriptions>

        <!-- 审核操作区域 -->
        <div class="action-area" v-if="currentDetail.status === 1">
          <el-divider content-position="left">审核操作</el-divider>
          <div class="action-buttons">
            <el-button type="success" @click="handleApprove(currentDetail)">
              <el-icon class="el-icon--left">
                <Check />
              </el-icon>
              审核通过
            </el-button>
            <el-button type="danger" @click="handleReject(currentDetail)">
              <el-icon class="el-icon--left">
                <Close />
              </el-icon>
              审核驳回
            </el-button>
          </div>
        </div>

        <!-- 完成操作区域 -->
        <div class="action-area" v-if="currentDetail.status === 2">
          <el-divider content-position="left">完成操作</el-divider>
          <div class="action-buttons">
            <el-button type="info" @click="handleComplete(currentDetail)">
              <el-icon class="el-icon--left">
                <Finished />
              </el-icon>
              标记完成
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :before-close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="form-dialog">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班日期" prop="scheduleDate">
              <el-date-picker v-model="formData.scheduleDate" type="date" placeholder="选择排班日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="formData.endDate" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="班次" prop="shiftId">
              <el-select v-model="formData.shiftId" placeholder="请选择班次" style="width: 100%">
                <el-option v-for="item in classOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="值班人员" prop="userId">
              <el-select v-model="formData.userId" placeholder="请选择值班人员" style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="周期类型" prop="cycleType">
              <el-select v-model="formData.cycleType" placeholder="请选择周期类型" style="width: 100%"
                @change="handleCycleTypeChange">
                <el-option v-for="item in cycleTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="周期值" prop="cycleValue">
              <el-select v-if="formData.cycleType === '1'" multiple v-model="formData.cycleValue" placeholder="请选择周期值"
                style="width: 100%">
                <el-option label="周一" value="周一" />
                <el-option label="周二" value="周二" />
                <el-option label="周三" value="周三" />
                <el-option label="周四" value="周四" />
                <el-option label="周五" value="周五" />
                <el-option label="周六" value="周六" />
                <el-option label="周日" value="周日" />
              </el-select>
              <el-select v-else-if="formData.cycleType === '2'" v-model="formData.cycleValue" multiple
                placeholder="请选择周期值" style="width: 100%">
                <el-option v-for="day in 31" :key="day" :label="`${day}日`" :value="`${day}`" />
              </el-select>
              <el-input v-else v-model="formData.cycleValue" placeholder="请输入周期值" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 顶班申请对话框 -->
    <el-dialog v-model="substituteDialogVisible" title="申请顶班" width="600px">
      <el-form ref="substituteFormRef" :model="substituteForm" :rules="substituteFormRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="被替班人员" prop="substituteUserId">
              <el-select v-model="substituteForm.substituteUserId" placeholder="请选择被替班人员" style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="排班日期" prop="scheduleDate">
              <el-date-picker v-model="substituteForm.scheduleDate" type="date" placeholder="选择排班日期"
                value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="班次" prop="shiftId">
              <el-select v-model="substituteForm.shiftId" placeholder="请选择班次" style="width: 100%">
                <el-option v-for="item in classOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="周期类型">
              <el-input v-model="substituteForm.cycleType" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="顶班原因" prop="substituteReason">
              <el-input v-model="substituteForm.substituteReason" type="textarea" :rows="3" placeholder="请输入顶班原因"
                maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="substituteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitSubstitute" :loading="submitting">
          提交申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

// API引入
import {
  getClassesList,
  getUserList,
  getCycleTypeList,
  getScheduleList,
  getScheduleDetail,
  addSchedule,
  updateSchedule,
  deleteSchedule,
  approveSchedule,
  rejectSchedule,
  completeSchedule
} from '@/api/prod_operate/prod_run/shift/scheduling'

// 搜索表单
const searchForm = reactive({
  scheduleDate: '',
  endDate: '',
  shiftId: '',
  userId: '',
  cycleType: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const classOptions = ref([])
const userOptions = ref([])
const cycleTypeOptions = ref([])

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const substituteDialogVisible = ref(false)
const dialogType = ref('add') // add/edit/view
const submitting = ref(false)

// 当前查看的详情数据
const currentDetail = ref(null)

// 表单引用
const formRef = ref()
const substituteFormRef = ref()

// 表单数据
const formData = reactive({
  id: '',
  scheduleDate: '',
  endDate: '',
  shiftId: '',
  userId: '',
  cycleType: '',
  cycleValue: '',
  remark: ''
})

// 顶班表单数据
const substituteForm = reactive({
  substituteUserId: '',
  scheduleDate: '',
  shiftId: '',
  cycleType: '3',
  substituteReason: ''
})

// 表单验证规则
const formRules = {
  scheduleDate: [{ required: true, message: '请选择排班日期', trigger: 'change' }],
  shiftId: [{ required: true, message: '请选择班次', trigger: 'change' }],
  userId: [{ required: true, message: '请选择值班人员', trigger: 'change' }],
  cycleType: [{ required: true, message: '请选择周期类型', trigger: 'change' }],
  cycleValue: [{ required: true, message: '请输入周期值', trigger: 'change' }]
}

const substituteFormRules = {
  substituteUserId: [{ required: true, message: '请选择被替班人员', trigger: 'change' }],
  scheduleDate: [{ required: true, message: '请选择排班日期', trigger: 'change' }],
  shiftId: [{ required: true, message: '请选择班次', trigger: 'change' }],
  substituteReason: [{ required: true, message: '请输入顶班原因', trigger: 'blur' }]
}

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await Promise.all([
      fetchClassesList(),
      fetchUserList(),
      fetchCycleTypeList()
    ])
    await fetchScheduleList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取班次列表
const fetchClassesList = async () => {
  try {
    const res = await getClassesList()
    classOptions.value = res.data || []
  } catch (error) {
    console.error('获取班次列表失败:', error)
    ElMessage.error('获取班次列表失败')
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList()
    userOptions.value = res.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取周期类型列表
const fetchCycleTypeList = async () => {
  try {
    const res = await getCycleTypeList()
    cycleTypeOptions.value = res.data || []
  } catch (error) {
    console.error('获取周期类型列表失败:', error)
    ElMessage.error('获取周期类型列表失败')
  }
}

// 获取排班列表
const fetchScheduleList = async () => {
  try {
    loading.value = true

    const params = {
      scheduleDate: searchForm.scheduleDate,
      endDate: searchForm.endDate,
      shiftId: searchForm.shiftId,
      userId: searchForm.userId,
      cycleType: searchForm.cycleType,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const res = await getScheduleList(params)

    tableData.value = res.rows
    pagination.total = res.total || 0
  } catch (error) {
    console.error('获取排班列表失败:', error)
    ElMessage.error('获取排班列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  fetchScheduleList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    scheduleDate: '',
    endDate: '',
    shiftId: '',
    userId: '',
    cycleType: ''
  })
  pagination.currentPage = 1
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  fetchScheduleList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增排班
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 申请顶班
const handleSubstitute = () => {
  resetSubstituteForm()
  // substituteDialogVisible.value = true
  handleAdd();
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getScheduleDetail(row.id)
    if (res.data) {
      currentDetail.value = res.data
      viewDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取排班详情失败:', error)
    ElMessage.error('获取排班详情失败')
  }
}

// 编辑排班
const handleEdit = async (row) => {
  try {
    const res = await getScheduleDetail(row.id)
    if (res.data) {
      Object.assign(formData, res.data)
      dialogType.value = 'edit'
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取排班详情失败:', error)
    ElMessage.error('获取排班详情失败')
  }
}

// 审核通过
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要通过该排班申请吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await approveSchedule(row.id)
    ElMessage.success('审核通过成功')
    fetchScheduleList()
    viewDialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核通过失败:', error)
      ElMessage.error('审核通过失败')
    }
  }
}

// 审核驳回
const handleReject = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要驳回该排班申请吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await rejectSchedule(row.id)
    ElMessage.success('审核驳回成功')
    fetchScheduleList()
    viewDialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核驳回失败:', error)
      ElMessage.error('审核驳回失败')
    }
  }
}

// 标记完成
const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要将该排班标记为已完成吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await completeSchedule(row.id)
    ElMessage.success('标记完成成功')
    fetchScheduleList()
    viewDialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      console.error('标记完成失败:', error)
      ElMessage.error('标记完成失败')
    }
  }
}

// 删除排班
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除排班记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteSchedule(row.id)
    ElMessage.success('删除成功')
    fetchScheduleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除排班失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedRows.value.map(item => item.id).join(',')
    await deleteSchedule(ids)
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    fetchScheduleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 处理周期类型变化
const handleCycleTypeChange = (value) => {
  formData.cycleValue = ''
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: '',
    scheduleDate: '',
    endDate: '',
    shiftId: '',
    userId: '',
    cycleType: '',
    cycleValue: '',
    remark: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 重置顶班表单
const resetSubstituteForm = () => {
  Object.assign(substituteForm, {
    substituteUserId: '',
    scheduleDate: '',
    shiftId: '',
    cycleType: '3',
    substituteReason: ''
  })
  if (substituteFormRef.value) {
    substituteFormRef.value.clearValidate()
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 关闭查看对话框
const handleCloseViewDialog = () => {
  viewDialogVisible.value = false
  currentDetail.value = null
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (dialogType.value === 'add') {
      await addSchedule(formData)
      ElMessage.success('新增成功')
    } else {
      await updateSchedule(formData)
      ElMessage.success('修改成功')
    }

    dialogVisible.value = false
    fetchScheduleList()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      // 验证错误，不显示消息
      return
    }
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 提交顶班申请
const handleSubmitSubstitute = async () => {
  if (!substituteFormRef.value) return

  try {
    await substituteFormRef.value.validate()
    submitting.value = true

    // 将顶班表单数据转换为排班表单格式
    const submitData = {
      ...substituteForm,
      userId: substituteForm.substituteUserId, // 顶班人员就是被替班人员
      cycleValue: substituteForm.scheduleDate, // 顶班时周期值就是日期
      status: '1' // 待审核状态
    }

    await addSchedule(submitData)
    ElMessage.success('顶班申请提交成功')
    substituteDialogVisible.value = false
    fetchScheduleList()
  } catch (error) {
    console.error('提交顶班申请失败:', error)
    if (error.errors) {
      return
    }
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchScheduleList()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchScheduleList()
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return dayjs(dateString).format('YYYY-MM-DD')
  } catch {
    return dateString
  }
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  try {
    return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return dateTimeString
  }
}

const getCycleTypeTag = (type) => {
  switch (type) {
    case '1': return 'primary'
    case '2': return 'success'
    case '3': return 'warning'
    default: return 'info'
  }
}

const getCycleTypeText = (type) => {
  const cycleType = cycleTypeOptions.value.find(item => item.id == type)
  return cycleType ? cycleType.name : type || '-'
}

const getStatusTag = (status) => {
  switch (status) {
    case 1: return 'warning' // 待审核
    case 2: return 'success' // 已生效
    case 3: return 'danger'  // 已驳回
    case 4: return 'info'    // 已完成
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1: return '待审核'
    case 2: return '已生效'
    case 3: return '已驳回'
    case 4: return '已完成'
    default: return status || '-'
  }
}

const getClassName = (shiftId) => {
  const classItem = classOptions.value.find(item => item.dictValue === shiftId)
  return classItem ? classItem.dictLabel : '-'
}

const getUserName = (userId) => {
  const userItem = userOptions.value.find(item => item.id === userId)
  return userItem ? userItem.name : '-'
}

const getName = (list, value, keyField, nameField) => {
  const item = list.find(item => item[keyField] === value)
  return item ? item[nameField] : '-'
}

// 计算属性
const dialogTitle = computed(() => {
  switch (dialogType.value) {
    case 'add': return '新增排班'
    case 'edit': return '编辑排班'
    case 'view': return '查看排班'
    default: return '排班信息'
  }
})
</script>

<style scoped lang="scss">
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.action-area {
  text-align: right;
}
</style>